import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_cookbook/ui/pages/DetailPage.dart';
import 'package:shared_preferences/shared_preferences.dart';

var _context;

class FavoritePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    _context = context;

    return MaterialApp(
      home: Favorite(),
    );
  }

}

class Favorite extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _Favorite();
  }

}

class _Favorite extends State {

  List<String> _favorite = [];

  SharedPreferences prefs;

  int allFavorite = 0;

  Widget none = Center(
    child: Text("你还没有收藏的菜谱！"),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            onPressed: () async {
              bool result = await showTipDialog();
              if (result) {
                setState(() {
                  _favorite.clear();
                });
              }
          },
            icon: Icon(
              Icons.delete
            )
          )
        ],
        centerTitle: true,
        title: Text("我的收藏"),
        leading: IconButton(onPressed: () {
          Navigator.of(_context).pop();
        }, icon: Icon(Icons.arrow_back)),
      ),
      body: _favorite.isEmpty ? none : Container(
        padding: EdgeInsets.all(4),
        child: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2
          ),
          itemBuilder: (BuildContext context, int index) {
            //print(_favorite[index]);
            var f = jsonDecode(_favorite[index]);

            return GestureDetector(
              onLongPress: () {
                setState(() {
                  _favorite.removeAt(index);
                });
              },
              onTap: () {
                Navigator.of(_context).push(MaterialPageRoute(builder: (context) {
                  return DetailPage(f);
                }));
              },
              child: Container(
                color: Colors.transparent,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Expanded(
                          flex: 3,
                          child: Center(
                            child: ClipRRect(
                                child: Image(
                                    image: NetworkImage(f["pic"])
                                ),
                                borderRadius: BorderRadius.circular(5)
                            ),
                          )
                      ),
                      Expanded(
                          flex: 1,
                          child: Container(
                            child: Center(
                              child: Text(f["name"], style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),),
                            ),
                          )
                      ),

                    ],
                  ),
                ),
              ),
            );
          },
          itemCount: _favorite.length,
          physics: BouncingScrollPhysics(),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();

    favoriteData();
  }

  @override
  void dispose() {
    super.dispose();

    saveData();
  }

  void saveData() {
    if (prefs != null && allFavorite != _favorite.length) {
      prefs.setStringList("favorite", _favorite);
    }
  }

  void favoriteData() async {
    prefs = await SharedPreferences.getInstance();
    List<String> _list = prefs.getStringList("favorite");
    if (_list != null) {
      _favorite.clear();
      setState(() {
        _favorite.addAll(_list);
        allFavorite = _favorite.length;
      });
    }
  }

  Future<bool> showTipDialog() {
    return showDialog(context: context, builder: (context) {
      return AlertDialog(
        title: Text("提示"),
        content: Text("清空所有收藏的菜谱"),
        actions: [
          TextButton(
            child: Text("取消"),
            onPressed: () => Navigator.of(context).pop(), //关闭对话框
          ),
          TextButton(
            child: Text("清空"),
            onPressed: () {
              Navigator.of(context).pop(true); //关闭对话框
            },
          ),
        ],
      );
    });
  }
}